package com.caunock.sqlbuilder.adapter.group;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.caunock.sqlbuilder.adapter.AbstractDDLAdapter;
import com.caunock.sqlbuilder.meta.Column;
import com.caunock.sqlbuilder.meta.Index;
import com.caunock.sqlbuilder.meta.Table;

import java.util.List;

/**
 * 兼容性遵循组
 * 组员: MySQL, SQLite, MariaDB
 *
 * @author Qinweitong
 */
public abstract class FlexibleGroupDDLAdapter extends AbstractDDLAdapter {
    @Override
    public String listDatabases() {
        return "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA";
    }

    @Override
    public String listTables(String schema) {
        return "SELECT TABLE_NAME FROM information_schema.TABLES where TABLE_SCHEMA  = '" + schema + "'";
    }

    @Override
    public StringBuilder increment(StringBuilder builder, Column<?> meta) {
        boolean autoIncrement = meta.isAutoIncrement();
        if (!autoIncrement) {
            return builder;
        }
        builder.append(" AUTO_INCREMENT ");
        return builder;
    }

    @Override
    public StringBuilder comment(StringBuilder builder, Table meta) {
        String comment = meta.getComment();
        if (StrUtil.isNotBlank(comment)) {
            builder.append(" COMMENT ").append(NAME_QUOTE).append(comment).append(NAME_QUOTE);
        }
        return builder;
    }

    @Override
    public StringBuilder comment(StringBuilder builder, Column<?> column) {
        String comment = column.getComment();
        if (StrUtil.isNotBlank(comment)) {
            builder.append(" COMMENT ").append(NAME_QUOTE).append(comment).append(NAME_QUOTE);
        }
        return builder;
    }

    @Override
    public StringBuilder indexes(StringBuilder builder, Table meta) {
        List<Index> indexes = meta.getIndexes();
        if (CollUtil.isEmpty(indexes)) {
            return builder;
        }
        for (Index index : indexes) {
            String comment = index.getComment();
            builder.append(BR);
            List<String> columnNames = index.getColumnNames();
            String name = index.getName();
            builder.append("ALTER TABLE ").append(meta.getName()).append(" ADD");
            builder.append(" INDEX ").append(name).append(" (").append(String.join(COMMA, columnNames)).append(")");
            if (StrUtil.isNotBlank(comment)) {
                builder.append(" COMMENT ").append(NAME_QUOTE).append(comment).append(NAME_QUOTE);
            }
            builder.append(";");
        }
        return builder;
    }
}
